package mdt;

import java.io.*;
import java.util.regex.*;
import mdt.util.*;

public class CodeParser
{
	File file;
	String content;

	Pattern commentPattern, stringPattern;
	StatePreservingMatcher commentMatcher, stringMatcher;
	int lastReturnedEnd = -1;

	public CodeParser(String _path) throws IOException
	{
		file = new File(_path);

		FileInputStream filestream = new FileInputStream(file);
		DataInputStream dis = new DataInputStream(filestream);

		byte[] byteContent = new byte[filestream.available()];
		dis.readFully(byteContent);
		content = new String(byteContent);

		dis.close();
		filestream.close();

		commentPattern = Pattern.compile(Configuration.MarkupCommentRegex);
		stringPattern = Pattern.compile(Configuration.StringRegex);
		commentMatcher = new StatePreservingMatcher(
				commentPattern.matcher(content));
		stringMatcher = new StatePreservingMatcher(
				stringPattern.matcher(content));

		commentMatcher.find();
		stringMatcher.find();
	}

	public MarkupComment nextComment()
	{
		while (commentMatcher.HasMatch())
		{
			//System.out.println(commentMatcher.start(3) + "/" + stringMatcher.start() + "\n" + commentMatcher.group() + "\n\n" + stringMatcher.group());
			
			
			if (commentMatcher.start(Configuration.MarkupCommentRegexStarting) < stringMatcher.start())
			{
				if (commentMatcher.start(Configuration.MarkupCommentRegexStarting) > lastReturnedEnd)
				{
					// Comments starts before the string -> parse and return
					String text = commentMatcher
							.group(Configuration.MarkupCommentRegexPreText)
							+ commentMatcher
									.group(Configuration.MarkupCommentRegexPostText);
					text = text.replaceAll("\t", "    ");
					String label = commentMatcher
							.group(Configuration.MarkupCommentRegexLabel);
					
					//Move intention of the text relative to the /*
					String indentation = commentMatcher.group(Configuration.MarkupCommentRegexIndentation);
					indentation = indentation.replaceAll("\t", "    ");
					
					text = text.replaceAll("(?m)^" + indentation, "");
					
					

					lastReturnedEnd = commentMatcher.end();
					commentMatcher.find();
					
					return new MarkupComment(text, label,
							file.getName(), file.getAbsolutePath());
				}
				else
				{
					//Current comment is part of last returned comment
					commentMatcher.find();
				}
			}
			else if (commentMatcher.start(Configuration.MarkupCommentRegexStarting) > stringMatcher.end())
			{
				// String ends before first comment -> go to next string
				stringMatcher.find();
			}
			else
			{
				// Overlapping string and comment
				commentMatcher.find();
			}
		}

		return null;
	}
}
